package cn.drh.charging.order.rabbitmq;


import cn.drh.charging.order.config.RabbitMQConfiguration;
import cn.drh.charging.order.pojo.po.OrderMQPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName RabbitMQOrderProduce
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/6/4 10:59
 * @Version 1.0
 */

@Slf4j
@Component
public class RabbitMQOrderProducer {
    //与rabbit
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到正常的订单队列
     * 正常的订单队列,没有消费者
     * 消息设置了生存时间
     * 消息过期后,超过了生存时间,消息会转发到死信队列
     *
     * @param orderMQPO 订单信息
     */
    public void sendOrder(OrderMQPO orderMQPO) {
        //设置RabbitMQ 退回的回调类 回执
        rabbitTemplate.setMandatory(true);
        //消息是发送exchange 收到后会转发到queue 当queue不存在，转发失败
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            //returnedMessage 包含被退掉的信息 包含消息本身，错误码，错误信息，交换机，路由key
            log.debug("returnedMessage会执行{}",returnedMessage);
        });

        //设置RabbitMQ 确认的回调类 保证不丢要在生产者开启confirm机制
        rabbitTemplate.setConfirmCallback(
                (correlationData, ack, cause) -> {
                    log.debug("Rabbit确认回调:{}",ack);
                    if (!ack) {
                        log.error("消息发送失败:{}", cause);
                    }else {
                        log.debug("消息发送成功");
                    }
                }
        );

        rabbitTemplate.convertAndSend(
                RabbitMQConfiguration.EXCHANGE_NAME,
                RabbitMQConfiguration.ROUTING_KEY,
                orderMQPO);
    }

}
